package com.bkgy.sys.menu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.sys.menu.dao.SysMenuDao;
import com.bkgy.sys.menu.entity.JSysMenu;
import com.bkgy.sys.menu.entity.SysMenu;
import com.bkgy.sys.menu.service.SysMenuService;
import com.bkgy.sys.role.dao.SysRoleDao;
import com.bkgy.sys.role.entity.SysRole;
import com.bkgy.sys.role.service.SysRoleService;
import com.bkgy.util.CodiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单接口具体实现类
 *
 * @author 生成器生成
 * @date 2019-01-11 16:58:55
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 添加记录
     *
     * @param data   json字符串
     * @param userId 用户id
     * @param sname  用户姓名
     */
    public ResultData insertDataSysMenu(String data, Long userId, String sname) {
        try {
            JSysMenu jmenu = JSON.parseObject(data, JSysMenu.class);
            SysMenu sysMenu = jmenu.getSysMenu();
            CodiUtil.newRecord(userId, sname, sysMenu);
            sysMenuDao.insertDataSysMenu(sysMenu);
            return ResultData.ResultDataSuccessSelf("添加数据成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("添加失败，错误信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键删除对象
     *
     * @param indocno 对象主键
     */
    public ResultData deleteDataSysMenuOne(Long indocno) {
        try {
            sysMenuDao.deleteDataSysMenuOne(indocno);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
        return ResultData.ResultDataSuccessSelf("删除数据数据成功", null);
    }

    /**
     * 根据主键字符串删除多个对象
     *
     * @param str_id 对象主键字符串
     */
    public ResultData deleteDataSysMenuMany(String str_id) {
        try {
            String sql = "delete sys_menu where indocno in(" + str_id + ")";
            sysMenuDao.deleteDataSysMenuMany(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
        return ResultData.ResultDataSuccessSelf("删除数据数据成功", null);
    }

    /**
     * 修改记录
     *
     * @param userId  用户id
     * @param sname   用户姓名
     * @param sysUser 对象实体
     */
    public ResultData updateDataSysMenu(String data, Long userId, String sname) {
        try {
            JSysMenu jmenu = JSON.parseObject(data, JSysMenu.class);
            SysMenu sysMenu = jmenu.getSysMenu();
            CodiUtil.editRecord(userId, sname, sysMenu);
            sysMenuDao.updateDataSysMenu(sysMenu);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 分页查看记录
     *
     * @param data 分页参数字符串
     */
    public ResultData findDataSysMenuByPage(String data) {
        try {
            JSysMenu jsysMenu = JSON.parseObject(data, JSysMenu.class);
            JSONObject jsonObject = null;
            Integer pageIndex = jsysMenu.getPageIndex();
            Integer pageSize = jsysMenu.getPageSize();

            if (null == pageIndex || null == pageSize) {
                return ResultData.ResultDataFaultSelf("分页参数没有传", null);
            }

            if (null != jsysMenu.getCondition()) {
                jsonObject = JSON.parseObject(jsysMenu.getCondition().toString());
            }

            String menuName = null;
            if (null != jsonObject.get("menu_name")) {
                menuName = jsonObject.get("menu_name").toString();
            }

            Long menuLevel = null;
            if (null != jsonObject.get("menu_level") && jsonObject.get("menu_level").toString().length() != 0) {
                menuLevel = Long.valueOf(jsonObject.get("menu_level").toString());
            }

           // List<SysMenu> list = sysMenuDao.findDataSysMenuByPage((pageIndex - 1) * pageSize, pageSize, menuName, menuLevel);
            List<SysMenu> list = sysMenuDao.findDataSysMenuByPage((pageIndex - 1) * pageSize, pageIndex*pageSize, menuName, menuLevel);

            Integer count = sysMenuDao.findDataSysMenuByPageSize(menuName, menuLevel);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键查询单个菜单记录
     *
     * @param data 分页参数字符串
     */
    public ResultData findDataSysMenuByIndocno(String data) {
        try {
            JSysMenu jsysMenu = JSON.parseObject(data, JSysMenu.class);
            Long indocno = jsysMenu.getIndocno();

            SysMenu sysMenu = sysMenuDao.findDataSysMenuByIndocno(indocno);
            return ResultData.ResultDataSuccess(sysMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 查看记录
     *
     * @return list 对象集合返回
     */
    public List<SysMenu> findDataSysMenu() {
        List<SysMenu> list = sysMenuDao.findDataSysMenu();
        return list;
    }

    /**
     * 用于获取一级菜单集合
     *
     * @param list 菜单的集合
     */
    @Override
    public List<SysMenu> findDataSysMenuFirstByUserId(Long userId) {
        String role_sql = "select r.* from sys_role r "
                + "left join sys_user_role sur on r.indocno = sur.role_id "
                + "where sur.user_id = " + userId;
        List<SysRole> roleList = sysRoleDao.findDataSysRoleByUserId(role_sql);

        if (roleList.size() > 0) {
            String role_list = "";

            for (SysRole role : roleList) {
                role_list += role.getIndocno() + ",";
            }
            role_list = role_list.substring(0, role_list.length() - 1);

            String menu_sql = "select distinct m.* from sys_menu m "
                    + "left join sys_role_menu srm on srm.menu_id = m.indocno "
                    + "where m.iparent = 0 and srm.role_id in (" + role_list + ") order by m.indocno asc";
            List<SysMenu> list = sysMenuDao.findDataSysMenuByRole(menu_sql);
            return list;
        }

        return null;
    }

    /**
     * 根据父菜单主键和人员id获取菜单子集合
     *
     * @param list 菜单的集合
     */
    @Override
    public List<SysMenu> findDataSysMenuChildByUserIdAndIparent(Long userId, Long iparent) {
        String role_sql = "select r.* from sys_role r "
                + "left join sys_user_role sur on r.indocno = sur.role_id "
                + "where sur.user_id = " + userId;
        List<SysRole> roleList = sysRoleDao.findDataSysRoleByUserId(role_sql);

        String role_list = "";

        for (SysRole role : roleList) {
            role_list += role.getIndocno() + ",";
        }
        role_list = role_list.substring(0, role_list.length() - 1);

        String menu_sql = "select distinct m.* from sys_menu m "
                + "left join sys_role_menu srm on srm.menu_id = m.indocno "
                + "where m.iparent = " + iparent + " and srm.role_id in (" + role_list + ") order by m.indocno asc";
        List<SysMenu> list = sysMenuDao.findDataSysMenuByRole(menu_sql);
        return list;
    }

    /**
     * 用于获取菜单集合
     *
     * @param list 菜单的集合
     */
    @Override
    public List<SysMenu> findDataSysMenuAllByUserId(Long userId) {
        String role_sql = "select r.* from sys_role r "
                + "left join sys_user_role sur on r.indocno = sur.role_id "
                + "where sur.user_id = " + userId;
        List<SysRole> roleList = sysRoleDao.findDataSysRoleByUserId(role_sql);

        String role_list = "";

        for (SysRole role : roleList) {
            role_list += role.getIndocno() + ",";
        }
        role_list = role_list.substring(0, role_list.length() - 1);

        String menu_sql = "select distinct m.* from sys_menu m "
                + "left join sys_role_menu srm on srm.menu_id = m.indocno "
                + "where m.iparent = 0 and srm.role_id in (" + role_list + ") order by m.indocno asc";
        List<SysMenu> list = sysMenuDao.findDataSysMenuByRole(menu_sql);
        getDataSysMenuTreeList(list, role_list);   //遍历添加子集集合
        return list;
    }



    /**
     * 递归获取菜单集合，用于获取一级节点的子集集合
     *
     * @param list 一级菜单的集合
     */
    public List<SysMenu> getDataSysMenuTreeList(List<SysMenu> list, String roleList) {
        List<SysMenu> subMenuList = new ArrayList<SysMenu>();
        String sql1 = "select distinct m.* from sys_menu m "
                + "left join sys_role_menu srm on srm.menu_id = m.indocno "
                + "where m.iparent = ";
        String sql2 = " and srm.role_id in (" + roleList + ") order by m.indocno asc";

        for (SysMenu entity : list) {
            List<SysMenu> childList = sysMenuDao.findDataSysMenuByIparent(sql1 + entity.getIndocno() + sql2);
            if (null != childList) {
                List<SysMenu> childMenuList = getDataSysMenuTreeList(childList, roleList);
                entity.setChild(childMenuList);
            }
            subMenuList.add(entity);
        }
        return subMenuList;
    }

    @Override
    public List<SysMenu> findAlwaysMenu(Long userId) {
        String role_sql = "select r.* from sys_role r "
                + "left join sys_user_role sur on r.indocno = sur.role_id "
                + "where sur.user_id = " + userId;
        List<SysRole> roleList = sysRoleDao.findDataSysRoleByUserId(role_sql);
        List<SysMenu> list = new ArrayList<>();
        if (roleList.size()>0 && !StringUtils.isEmpty(roleList)) {
            String role_list = "";

            for (SysRole role : roleList) {
                role_list += role.getIndocno() + ",";
            }
            role_list = role_list.substring(0, role_list.length() - 1);

            String menu_sql = "select distinct m.* from sys_menu m "
                    + "left join sys_role_menu srm on srm.menu_id = m.indocno "
                    + "where m.menu_level > 2 and srm.always_menu = 1 and srm.role_id in (" + role_list + ") order by m.indocno asc";
            list = sysMenuDao.findDataSysMenuByRole(menu_sql);
        }else {
            list = null;
        }
        return list;
    }
}
